package com.chen.shopping_admin_service.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.shopping_admin_service.mapper.AdminMapper;
import com.chen.shopping_common.pojo.Admin;
import com.chen.shopping_common.pojo.Permission;
import com.chen.shopping_common.service.AdminService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@DubboService
@Transactional
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public void addAdmin(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void deleteAdmin(Long aid) {
        adminMapper.deleteAdminRole(aid);
        adminMapper.deleteById(aid);
    }

    @Override
    public void updateAdmin(Admin admin) {
        if (!StringUtils.hasText(admin.getPassword())){
            String password = adminMapper.selectById(admin.getAid()).getPassword();
            admin.setPassword(password);
        }
        adminMapper.updateById(admin);
    }

    @Override
    public Admin findAdminById(Long aid) {
        Admin admin = adminMapper.findAdminById(aid);
        return admin;
    }

    @Override
    public Page<Admin> findAdminByPage(int page, int size) {
        Page<Admin> adminPage = adminMapper.selectPage(new Page(page, size), null);
        return adminPage;
    }

    @Override
    public void updateAdminRole(Long aid, Long[] rids) {
        //先删除管理员的所有角色
        adminMapper.deleteAdminRole(aid);
        //再添加角色
        for (Long rid : rids) {
            adminMapper.updateAdminRole(aid,rid);
        }
    }

    @Override
    public Admin findAdminByUsername(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public List<Permission> findPermissionByUsername(String username) {
        List<Permission> permissionByUsername = adminMapper.findPermissionByUsername(username);
        return permissionByUsername;
    }
}
